package org.vectrics.recruiter.struts.admin.job;

import java.util.Collection;
import java.util.Iterator;

import org.vectrics.DataException;
import org.vectrics.common.html.Combo;
import org.vectrics.domain.Domain;
import org.vectrics.location.Location;
import org.vectrics.provider.CoreServiceLocator;

public class LocationCombo extends Combo {

	private static final long serialVersionUID = -3857256819827929703L;
	
	private boolean showIndents = true;
	
	public LocationCombo(Domain domain, String locationType, boolean showIndents) {
		super();
		this.showIndents = showIndents;
		try {
			Collection allLocations = CoreServiceLocator.getLocationService()
					.findTopLevelLocations(domain, locationType);
			Iterator iter = allLocations.iterator();
			while (iter.hasNext()) {
				Location location = (Location)iter.next();
				this.displayLocation(location, 0);
			}
		}
		catch (Exception de) {
			log.error("Exception finding locations", de);
			throw new DataException("Exception finding locations", de);
		}
		
	}
	
	private void displayLocation(Location location, int nodeLevel) {
		this.addOption(getIndentedName(nodeLevel, location), location.getId().toString());
		displayChildren(location, nodeLevel);
	}

	
	private void displayChildren(Location parentLocation, int parentLevel) {
		Collection children = CoreServiceLocator.getLocationService().findChildren(parentLocation);
		Iterator iter = children.iterator();
		while (iter.hasNext()) {
			Location childLocation = (Location)iter.next();
			displayLocation(childLocation, parentLevel + 1);
		}
	}
	
	private String getIndentedName(int nodeLevel, Location location) {
		log.debug("getIndentedName() - method to indent displayed location name in the combo box");
		String indentedName = "";
		
		if (this.showIndents) {
			for (int i = 0; i < nodeLevel; i++) {
				indentedName += " -";
			}
		}
		indentedName += location.getName();
		log.debug("getIndentedName() - done");
		return(indentedName);
	}
	
}
